

package info.marlan.sipgate;



import info.marlan.sipgate.model.OwnUri;
import info.marlan.sipgate.model.SipgateAccount;
import info.marlan.util.ConvertUtil;
import info.marlan.util.DBHelper;
import info.marlan.util.TopExceptionHandler;

import java.net.URI;
import java.util.ArrayList;
import java.util.List;

import org.xmlrpc.android.XMLRPCClient;
import org.xmlrpc.android.XMLRPCException;
import org.xmlrpc.android.XMLRPCMethod;
import org.xmlrpc.android.XMLRPCMethodCallback;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.appwidget.AppWidgetManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.Spinner;
/**
 * 
 * @author mark@marlan.info
 *
 */



public class AppWidgetConfigure extends Activity {
	public static String KEY_PREFERENCES_INTERVAL = "info.marlan.sipgate.interval";
	public static String KEY_PREFERENCES_FROM = "info.marlan.sipgate.from";
	public static String KEY_PREFERENCES_TO = "info.marlan.sipgate.to";
	public static final int DIALOG_MISSING_USERNAME = 0;
	public static final int DIALOG_MISSING_PASSWORD = 1;
	public static final int DIALOG_INVALID_USERNAME_OR_PASSWORD = 3;
	public static final int DIALOG_NO_CONNECTION = 4;
	public static final int DIALOG_ERROR = 5;
	public static final int DIALOG_INVALID_UPDATE_INTERVAL = 6;
	public static final int DIALOG_XML_METHOD_ERROR = 7;
	public static final int DIALOG_SELECT_ENDPOINT = 8;
	
    private int appWidgetId = AppWidgetManager.INVALID_APPWIDGET_ID;
    private EditText userName;
    private EditText password;
    private CheckBox notify;
    private Spinner accounts;
    private Spinner status;
    private Spinner tos;
    private Spinner interval;
    private Spinner from;
    private Spinner to;
    private DBHelper dbHelper;
    private SharedPreferences preferences;
    private SipgateAccount account;
    private String errormessage;
    private View appwidgetAccount;
    private View appwidgetDetail;
    private ProgressDialog progressDialog;
    private RadioButton team;
    private RadioButton basic;
    
    
    public AppWidgetConfigure() {
        super();
    }

    @Override
	protected void onDestroy() {
		super.onDestroy();
		if(dbHelper!=null){
		dbHelper.cleanup();
		dbHelper=null;
		}
	}

	@Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        Thread.setDefaultUncaughtExceptionHandler(new TopExceptionHandler(this));
        checkForCrashReport();
        dbHelper  = new DBHelper(this);
        
        setResult(RESULT_CANCELED);

        
        setContentView(R.layout.appwidget_configure);
    	preferences = PreferenceManager
		.getDefaultSharedPreferences(this);
   
        userName = (EditText)findViewById(R.id.appwidget_username);
        password = (EditText)findViewById(R.id.appwidget_password);
        notify 	 = (CheckBox)findViewById(R.id.appwidget_notify);
        accounts = (Spinner) findViewById(R.id.account);
        status = (Spinner) findViewById(R.id.status);
        tos = (Spinner) findViewById(R.id.tos);
        basic = (RadioButton) findViewById(R.id.radio1);
        team = (RadioButton) findViewById(R.id.radio2);
        
        
        interval = (Spinner) findViewById(R.id.update_interval);
        from = (Spinner) findViewById(R.id.update_from);
        to = (Spinner) findViewById(R.id.update_to);
        
        appwidgetAccount = (View) findViewById(R.id.appwidget_account);
        appwidgetDetail = (View) findViewById(R.id.appwidget_detail);
        
        findViewById(R.id.save_button).setOnClickListener(mOnClickListener);


        Intent intent = getIntent();
        Bundle extras = intent.getExtras();
        if (extras != null) {
            appWidgetId = extras.getInt(
                    AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);
        }

       
        if (appWidgetId == AppWidgetManager.INVALID_APPWIDGET_ID) {
            finish();
        }
        account = dbHelper.getAccount(appWidgetId);
        if(account==null){
        	account = new SipgateAccount();
        }else{
        	userName.setText(account.getUserName());
            password.setText(account.getPassword());
            notify.setChecked(account.isNotify());
        }
        notify.setChecked(true);
    }

    View.OnClickListener mOnClickListener = new View.OnClickListener() {
        public void onClick(View v) {


            String userNameText = userName.getText().toString();
            String passwordText = password.getText().toString();
            if(userNameText==null || "".equals(userNameText)){
            	showDialog(DIALOG_MISSING_USERNAME);
            	return;
            }
            if(passwordText==null || "".equals(passwordText)){
            	showDialog(DIALOG_MISSING_PASSWORD);
            	return;
            }
            if(team.isChecked()){
            	account.setEndpoint(SipGateService.ENDPOINT_TEAM);
            }
            if(basic.isChecked()){
            	account.setEndpoint(SipGateService.ENDPOINT_BASIC);
            }
            if("".equals(account.getEndpoint()) || account.getEndpoint() == null){
            	showDialog(DIALOG_SELECT_ENDPOINT);
            	return;	
            }
            account.setNotify(notify.isChecked());
            account.setUserName(userNameText);
            account.setPassword(passwordText);
            account.setWidgetId(appWidgetId);
            
            AppWidgetConfigure.this.progressDialog = ProgressDialog
			.show(
					AppWidgetConfigure.this,
					getString(R.string.connecting),
					getString(R.string.searching_sip_number));
            getOwnUris(AppWidgetConfigure.this,appWidgetId);

        }
    };

    @Override
	protected Dialog onCreateDialog(int id) {

		switch (id) {
		case DIALOG_MISSING_USERNAME:
			return new AlertDialog.Builder(AppWidgetConfigure.this).setTitle(
					getString(R.string.dialog_title)).setMessage(
					getString(R.string.dialog_missing_username))
					.setPositiveButton(android.R.string.ok,
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int which) {

								}
							}).create();
			case DIALOG_MISSING_PASSWORD:
			return new AlertDialog.Builder(AppWidgetConfigure.this).setTitle(
					getString(R.string.dialog_title)).setMessage(
					getString(R.string.dialog_missing_password))
					.setPositiveButton(android.R.string.ok,
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int which) {
	
								}
							}).create();
			case DIALOG_INVALID_USERNAME_OR_PASSWORD:
				return new AlertDialog.Builder(AppWidgetConfigure.this).setTitle(
						getString(R.string.dialog_title)).setMessage(
						getString(R.string.dialog_invalid_username_password))
						.setPositiveButton(android.R.string.ok,
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int which) {
		
									}
								}).create();
			case DIALOG_NO_CONNECTION:
				return new AlertDialog.Builder(AppWidgetConfigure.this).setTitle(
						getString(R.string.dialog_title)).setMessage(
						getString(R.string.dialog_invalid_username_password))
						.setPositiveButton(android.R.string.ok,
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int which) {
		
									}
								}).create();
			case DIALOG_ERROR:
				return new AlertDialog.Builder(AppWidgetConfigure.this).setTitle(
						getString(R.string.dialog_title)).setMessage(
						getString(R.string.dialog_error))
						.setPositiveButton(android.R.string.ok,
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int which) {
		
									}
								}).create();
			case DIALOG_INVALID_UPDATE_INTERVAL:
				return new AlertDialog.Builder(AppWidgetConfigure.this).setTitle(
						getString(R.string.dialog_title)).setMessage(
						getString(R.string.dialog_invalid_update_interval))
						.setPositiveButton(android.R.string.ok,
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int which) {
		
									}
								}).create();
			case DIALOG_XML_METHOD_ERROR:
				return new AlertDialog.Builder(AppWidgetConfigure.this).setTitle(
						getString(R.string.dialog_title)).setMessage(
						errormessage)
						.setPositiveButton(android.R.string.ok,
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int which) {
		
									}
								}).create();
				
			case DIALOG_SELECT_ENDPOINT:
				return new AlertDialog.Builder(AppWidgetConfigure.this).setTitle(
						getString(R.string.dialog_title)).setMessage(
								getString(R.string.dialog_select_endpoint))
						.setPositiveButton(android.R.string.ok,
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int which) {
		
									}
								}).create();
		}
		return null;
	}

    
    void getOwnUris(final Context context, 
           final int appWidgetId) {
    	
    	XMLRPCClient client = new XMLRPCClient(URI.create(account.getEndpoint()), account.getUserName(), account.getPassword());
    	
        XMLRPCMethod method = new XMLRPCMethod("samurai.OwnUriListGet", new XMLRPCMethodCallback() {
  			public void callFinished(Object result) {
  				try{
  				List<OwnUri> entries = ConvertUtil.getOwnUriList(result,appWidgetId);
  				account.setOwnUriList(entries);
  				displayDetail();
  				}catch (XMLRPCException e) {
  					errormessage = e.getMessage();
					showDialog(DIALOG_XML_METHOD_ERROR);
				}
  			}
          },
          client,
          handler
          );
          
               
          method.call(null);
    }

	public void displayDetail() {
		if (AppWidgetConfigure.this.progressDialog != null
				&& AppWidgetConfigure.this.progressDialog
						.isShowing()) {
			AppWidgetConfigure.this.progressDialog.dismiss();
		}
		List<String> sipUris = new ArrayList<String>();
		sipUris.add(getString(R.string.all));
		for(OwnUri uri : account.getOwnUriList()){
			sipUris.add(uri.getSipUri());
		}
		 ArrayAdapter<String> accountsAdapter = new ArrayAdapter<String>(this, 
				 android.R.layout.simple_spinner_item, sipUris  ); 
		 accounts.setOnItemSelectedListener(accountListener);
		
		accountsAdapter
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		accounts.setAdapter(accountsAdapter);
		
		ArrayAdapter<CharSequence> statusAdapter = ArrayAdapter
		.createFromResource(this, R.array.status,
				android.R.layout.simple_spinner_item);
		statusAdapter
		.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		status.setAdapter(statusAdapter);
		status.setOnItemSelectedListener(statusListener);
		
		ArrayAdapter<CharSequence> tosAdapter = ArrayAdapter
		.createFromResource(this, R.array.tos,
				android.R.layout.simple_spinner_item);
		tosAdapter
		.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		tos.setAdapter(tosAdapter);
		tos.setOnItemSelectedListener(tosListener);
		
		
		ArrayAdapter<CharSequence> intervalAdapter = ArrayAdapter
		.createFromResource(this, R.array.updateinterval,
				android.R.layout.simple_spinner_item);
		intervalAdapter
		.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		interval.setAdapter(intervalAdapter);
		interval.setOnItemSelectedListener(intervalListener);
		
		ArrayAdapter<CharSequence> fromAdapter = ArrayAdapter
		.createFromResource(this, R.array.updatetime,
				android.R.layout.simple_spinner_item);
		fromAdapter
		.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		from.setAdapter(fromAdapter);
		from.setOnItemSelectedListener(fromListener);
		
		ArrayAdapter<CharSequence> toAdapter = ArrayAdapter
		.createFromResource(this, R.array.updatetime,
				android.R.layout.simple_spinner_item);
		toAdapter
		.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		to.setAdapter(toAdapter);
		to.setOnItemSelectedListener(toListener);
		
		init();
		appwidgetAccount.setVisibility(View.GONE);
		appwidgetDetail.setVisibility(View.VISIBLE);
		findViewById(R.id.savedetail_button).setOnClickListener( new View.OnClickListener() {
	        public void onClick(View v) {
	            final Context context = AppWidgetConfigure.this;
	            if(!isSelectionValid()){
	            	return;
	            }
	            dbHelper.addAccount(account);
	            Intent resultValue = new Intent();
	            resultValue.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
	            setResult(RESULT_OK, resultValue);
	            finish();
	            context.startService(new Intent(context, SipGateService.class));
	        }
		});
	}
	
	public boolean isSelectionValid(){
		int from = preferences.getInt(KEY_PREFERENCES_FROM, 7) + 1;
		int to = preferences.getInt(KEY_PREFERENCES_TO, 21) + 1;
		if((to-from)<4){
			showDialog(DIALOG_INVALID_UPDATE_INTERVAL);
			return false;
		}
		
		return true;
	}
	
	public void init(){
		account.setNotify(true);
		account.setNotifyStatus(0);
		account.setNotifyTos(0);
		account.setSipgateUri(SipGateService.STRING_ALL);
		interval.setSelection( preferences.getInt(KEY_PREFERENCES_INTERVAL,1));
		from.setSelection(preferences.getInt(KEY_PREFERENCES_FROM,7));
		to.setSelection(preferences.getInt(KEY_PREFERENCES_TO,21));
	}
	
	public AdapterView.OnItemSelectedListener statusListener = new AdapterView.OnItemSelectedListener() {
		public void onItemSelected(AdapterView<?> parent, View v, int position,
				long id) {
			
			account.setNotifyStatus(position);
		}

		public void onNothingSelected(AdapterView<?> parent) {
			
		}
	};
	
	public AdapterView.OnItemSelectedListener tosListener = new AdapterView.OnItemSelectedListener() {
		public void onItemSelected(AdapterView<?> parent, View v, int position,
				long id) {
			
			account.setNotifyTos(position);
		}

		public void onNothingSelected(AdapterView<?> parent) {
		
		}
	};
	public AdapterView.OnItemSelectedListener accountListener = new AdapterView.OnItemSelectedListener() {
		public void onItemSelected(AdapterView<?> parent, View v, int position,
				long id) {
			
			if(position==0){
				account.setSipgateUri(SipGateService.STRING_ALL);	
			}else{
				account.setSipgateUri(account.getOwnUriList().get(position-1).getSipUri());
			}
			
		}

		public void onNothingSelected(AdapterView<?> parent) {
			
		}
	};
	public AdapterView.OnItemSelectedListener intervalListener = new AdapterView.OnItemSelectedListener() {
		public void onItemSelected(AdapterView<?> parent, View v, int position,
				long id) {
			
			Editor preferencesEditor = preferences.edit();
            preferencesEditor.putInt(KEY_PREFERENCES_INTERVAL, position);
        	preferencesEditor.commit();  
		}

		public void onNothingSelected(AdapterView<?> parent) {
			
		}
	};
	public AdapterView.OnItemSelectedListener fromListener = new AdapterView.OnItemSelectedListener() {
		public void onItemSelected(AdapterView<?> parent, View v, int position,
				long id) {
			Editor preferencesEditor = preferences.edit();
            preferencesEditor.putInt(KEY_PREFERENCES_FROM, position);
        	preferencesEditor.commit();  
		}

		public void onNothingSelected(AdapterView<?> parent) {
			
		}
	};
	public AdapterView.OnItemSelectedListener toListener = new AdapterView.OnItemSelectedListener() {
		public void onItemSelected(AdapterView<?> parent, View v, int position,
				long id) {
			Editor preferencesEditor = preferences.edit();
            preferencesEditor.putInt(KEY_PREFERENCES_TO, position);
        	preferencesEditor.commit();  
		}

		public void onNothingSelected(AdapterView<?> parent) {
		
		}
	};
	
	@Override
	protected void onPause() {
		super.onPause();
		if (progressDialog != null && progressDialog.isShowing()) {
			progressDialog.dismiss();
		}
	}

	private final Handler handler = new Handler() {
		@Override
		public void handleMessage(final Message msg) {
			if (AppWidgetConfigure.this.progressDialog != null
					&& AppWidgetConfigure.this.progressDialog.isShowing()) {
				AppWidgetConfigure.this.progressDialog.dismiss();
			}
			//String message = msg.getData().getString(XMLRPCMethod.ERROR_MESSAGE);
			int nr = msg.getData().getInt(XMLRPCMethod.ERROR_NR,0);
			
			if(nr==XMLRPCMethod.STATUSCODE_UNAUTHORIZED){
				showDialog(DIALOG_INVALID_USERNAME_OR_PASSWORD);
			}else if(nr==XMLRPCMethod.STATUSCODE_NO_CONNECTION){
				showDialog(DIALOG_NO_CONNECTION);
			}else{
				showDialog(DIALOG_ERROR);
			}
			//Log.v(WidgetProvider.LOGTAG, msg.getData().getInt(XMLRPCMethod.ERROR_NR));
		}
	};

    public void notifyUser(String title, String message, Intent intent){
    	NotificationManager notificationManager = 
    		(NotificationManager)getSystemService(
    		Context.NOTIFICATION_SERVICE);
    	
    	Notification notification = new Notification( 
    			android.R.drawable.stat_notify_error,message,
    			System.currentTimeMillis());
    	long[] vibration = new long[]{100,500,250,1000};
    	notification.vibrate = vibration;
    	
    	PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), 0, intent,PendingIntent.FLAG_UPDATE_CURRENT);
    	notification.setLatestEventInfo(getApplicationContext(),title,message, pendingIntent);
    	//Log.v(WidgetProvider.LOGTAG, "NotifyUser");
    	notificationManager.notify(123456, notification);
    }
    
    public void checkForCrashReport(){
    	if(!CrashReportActivity.fileExists(CrashReportActivity.CRASHREPORT, this)){
    		return;
    	}
    	Intent intent = new Intent (getApplication(),CrashReportActivity.class); 
    	//intentToSaveRecord.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
    	//startActivity(intentToSaveRecord); 
    	notifyUser(getString(R.string.crnotifytitle),getString(R.string.crnotifymessage), intent);
    }

}
